package com.vastio.boot.filter;

import org.apache.shiro.web.filter.authc.UserFilter;
import org.apache.shiro.web.util.WebUtils;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author hjwStart
 * @time 2022-12-19 16:40
 * @version: 1.0
 */
public class ApiFilter extends UserFilter {

    private static final String ERROR_JSON = "{\"code\":401,\"url\":\"http://localhost:8080\"}";

    /**
     * return error message, instead of redirect to login page
     */
    @Override
    protected boolean onAccessDenied(ServletRequest req, ServletResponse response) throws Exception {
        HttpServletRequest request = (HttpServletRequest) req;

        HttpServletResponse httpResponse = WebUtils.toHttp(response);// <==> (HttpServletResponse) response
        httpResponse.setStatus(HttpServletResponse.SC_OK);

        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        response.getWriter().printf(ERROR_JSON, request.getRequestURI());

        return false;
    }
}
